"""
http://127.0.0.1:8000/latticeqcd/ildg/domains.json
http://127.0.0.1:8000/latticeqcd/ildg/ensembles.json/ukqcd
http://127.0.0.1:8000/latticeqcd/ildg/ensemble.json/ukqcd/ukqcd/DWF/ensemble1
http://127.0.0.1:8000/latticeqcd/ildg/file_info.json/ukqcd/ukqcd/DWF/ensemble1/ensemble1.10
"""
import ildg_soap

response.generic_patterns=['json','xml']

def url(a,args=[]):
    if request.extension=='html':
        return args
    elif request.extension=='xml':
        return 'http://'+request.env.http_host+URL(a+'.xml',args=args)
    else:

        return 'http://'+request.env.http_host+URL(a+'.json',args=args)

#@cache(request.env.path_info,600)
def index():
    ensembles={}
    domains = ildg_soap.domains()
    for name,status in domains:
        ensembles[name]=[]
    import urllib
    for row in db(db.ensemble).select(orderby=db.ensemble.path):
        domain = row.path.split('/')[0].lower()
        ensembles[domain].append(row.path)
    return locals()

# @cache(request.env.path_info,3600)
def domains():
    domains = [(url('ensembles',x),
                db(db.ensemble.path.startswith(x)).count(),y) \
                   for x,y in ildg_soap.domains()]
    return dict(domains=domains)

#@cache(request.env.path_info,3600)
def ensembles():
    e = db.ensemble
    rows = db(e.path.startswith(request.args(0))).select(orderby=e.path)
    ensembles = [url('ensemble',row.path) for row in rows]    
    return dict(ensembles = ensembles)


def learn():
    import ildg_soap
    domains = ildg_soap.domains()
    ensembles = []
    for domain,status in domains:
        ensembles += ildg_soap.ensembles(domain) if status else []
        for ensemble in ensembles:
            db(db.ensemble.path==ensemble).delete()
            if not db.ensemble(path=ensemble):
                id = db.ensemble.insert(path=ensemble)
                info = simplify(ildg_soap.Ensemble(ensemble).info())
                #db(db.parameter).delete()
                for key, value in info:
                    if not key in ('files','files.files'):
                        db.parameter.insert(ensemble=id,key=key,value=value)
    return repr(ensembles)

def search():
    form = SQLFORM.factory(Field('keywords',
                                 default=request.vars.keywords,
                                 requires=IS_NOT_EMPTY()))
    e, p = db.ensemble, db.parameter
    if request.vars.keywords:
        form.vars.keywords = request.vars.keywords
        kv = [x.strip() for x in request.vars.keywords.split('and')]
        q = reduce(lambda a,b:a&b, [(p.key.endswith(key)&p.value.contains(value)) for key,value in [(['']+x.split())[-2:] for x in kv]])
        rows = db(q)(p.ensemble==e.id).select(e.path,distinct=True,
                                             orderby=e.path)
    else: rows=[]
    return dict(form=form, rows=rows)

#@cache(request.env.path_info,3600)
def ensemble():
    path = request.vars.path
    ensemble = db.ensemble(path=path)
    rows = db(db.parameter.ensemble==ensemble.id)\
        .select(orderby=db.parameter.key)
    try:
        files = ildg_soap.Ensemble(path).files()        
        files = [url('file_info',path+'/'+x) for x in files]
    except:
        files = []
    domain = url('ensembles',request.args(0))
    return dict(rows=rows,domain=domain,files=files)

#@cache(request.env.path_info,3600)
def file_info():
    fullpath = request.vars.path
    path,filename = '/'.join(fullpath[:-1]), fullpath[-1]
    info = ildg_soap.Ensemble(path).info(filename)
    info['ensemble'] = url('ensemble',path)
    return dict(info=info)

def keys():
    rows = db(db.parameter).select(db.parameter.key,distinct=True,
                                   orderby=db.parameter.key,
                                   cache=(cache.ram,3600))
    return dict(rows=rows)

def values():
    count = db.parameter.id.count()
    rows = db(db.parameter.key==request.vars.key).select(
        db.parameter.value,count,groupby=db.parameter.value,
        orderby=db.parameter.value)
    return dict(rows=rows,count=count)
